package com.mox.enterprise.crawler;

import com.google.gson.Gson;
import com.mox.enterprise.common.ApiDao;
import com.mox.enterprise.common.ApiInDao;
import com.mox.enterprise.constants.CommonConstants;
import com.mox.enterprise.dao.Company;
import com.mox.enterprise.dao.CompanyInfoDao;
import com.mox.enterprise.enums.ApiCode;
import com.mox.enterprise.factory.SqlSessionFactoryUtil;
import com.mox.enterprise.mapper.CompanyMapper;
import com.mox.enterprise.service.RemoteService;
import com.mox.enterprise.util.JedisUtil;
import com.mox.enterprise.util.Network;
import com.mox.enterprise.util.RedisOpera;
import com.mox.enterprise.util.YamlReader;
import io.reactivex.Observable;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

/**
 * @author mox
 * @time 2020/2/17 0:03
 */
@Slf4j
public class QccCrawler {

    private static RemoteService remoteService;

    private static SqlSessionFactory factory = SqlSessionFactoryUtil.sessionFactory;

    private static SqlSession sqlSession;

    static {
        remoteService = Network.remoteService();
        sqlSession = factory.openSession(true);
    }

    public static void getQccInfo() {
        Map load = null;
        Map qcc = null;
        try {
            load = YamlReader.load("param.yml");
            qcc = (Map) load.get("QCC");
            if (qcc != null) {

                Integer pageIndex = Integer.parseInt(qcc.get(CommonConstants.PAGE_INDEX).toString());
                while (true) {
                    if (CommonConstants.ONE.equals(pageIndex)) {
                        getQccInfo(qcc);
                        log.info("第{}页数据获取成功", pageIndex);
                    } else {
                        qcc.put(CommonConstants.PAGE_INDEX, pageIndex);
                        getQccInfo(qcc);
                        log.info("第{}页数据获取成功", pageIndex);
                    }
                    pageIndex++;
                    Thread.sleep(3000);
                }
            }

        } catch (IOException e) {
            log.error("yaml数据读取失败:{}", e.getMessage());
        } catch (InterruptedException e) {
            log.error("线程暂停失效:{}", e.getMessage());
        }

    }

    private static void getQccInfo(Map qcc) {
        if (qcc != null) {
            CompanyMapper mapper = sqlSession.getMapper(CompanyMapper.class);

            Observable<ApiDao> qyInfo = remoteService.getQYInfo(qcc);
            qyInfo.subscribe(apiDao -> {
                        if (ApiCode.SUCCESS.getStatus().equals(apiDao.getStatus())) {
                            Gson gson = new Gson();
                            ApiInDao apiInDao = gson.fromJson(gson.toJson(apiDao.getResult()), ApiInDao.class);

                            ArrayList results = gson.fromJson(gson.toJson(apiInDao.getResult()), ArrayList.class);

                            for (Object result : results) {
                                CompanyInfoDao companyInfoDao = gson.fromJson(gson.toJson(result), CompanyInfoDao.class);

                                if (!"".equals(companyInfoDao.getContactNumber())) {
                                    log.info("获取到含有联系方式的企业数据:{},{}", companyInfoDao.getOperName(), companyInfoDao.getContactNumber());
                                    Company company = new Company();
                                    company.setOperName(companyInfoDao.getOperName());
                                    company.setName(companyInfoDao.getName());
                                    company.setAddress(companyInfoDao.getAddress());
                                    company.setEmail(companyInfoDao.getEmail());
                                    company.setContactNumber(companyInfoDao.getContactNumber());
                                    company.setCreditCode(companyInfoDao.getCreditCode());
                                    company.setTag(companyInfoDao.getTag());
                                    company.setKeyNo(companyInfoDao.getKeyNo());
                                    company.setStatus(companyInfoDao.getStatus());
                                    company.setDate(new Date());

                                    try {
                                        if (RedisOpera.get(company.getKeyNo()) == null) {
                                            int insert = mapper.insert(company);
                                            if (insert > 0) {
                                                log.info("数据插入成功:{}", gson.toJson(company));
                                                RedisOpera.setnx(company.getKeyNo(), company.getCreditCode());
                                            }
                                            Thread.sleep(2000);
                                        } else {
                                            log.info("数据已存在");
                                        }
                                    } catch (Exception e) {
                                        log.error("数据库操作失败:{}", e.getMessage());
                                    }
                                }

                            }
                        } else if (ApiCode.TOKEN_INVALID.getStatus().equals(apiDao.getStatus())) {
                            log.error(apiDao.getMessage());
                            System.exit(0);
                        }
                    },
                    throwable -> {
                        log.error("数据获取出错:{}", throwable.getCause().toString());
                    },
                    () -> {
                        log.info("数据获取成功");
                    }).dispose();

        }
    }

}
